package org.samcolon.spring_security.demo1;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

/**
 * @Description:
 * @author: Sam.zhang
 * @date: 2022/2/15 - 20:06
 */
public class MyAuthProvider implements AuthenticationProvider {
    /**
     * 权限效验
     * @param authentication
     * @return
     * @throws AuthenticationException
     */

    @Resource
    private MyUserDetailsService userDetailsService;

    private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        // 参数传输的用户名
        String username = authentication.getPrincipal().toString();
        // 参数传输的密码
        String rawPassword = authentication.getCredentials().toString();

        // 通过配制的用户服务，获得用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        // 对比密码是否相同，rawPassword为明文密码
        if(encoder.matches(rawPassword, userDetails.getPassword())){
            UsernamePasswordAuthenticationToken token =
                    new UsernamePasswordAuthenticationToken(username, userDetails.getPassword(), userDetails.getAuthorities());
            return token;
        } else {
            throw new BadCredentialsException("用户名或密码错误");
        }
    }

    /**
     * 是否支持自定义的配制
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
